package com.ogawa.chair7808.ui.activity

import android.text.TextUtils
import com.blankj.utilcode.util.GsonUtils
import com.blankj.utilcode.util.LogUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.ogawa.base.Constant.CommmandNum
import com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_END_TIME
import com.ogawa.base.Constant.Constant.LIVE_EVENT_BUS_KEY_UPDATE_TIME
import com.ogawa.base.Constant.MqttConstant.EVENT_BUS_KEY_RECEIVE_MESSAGE
import com.ogawa.base.Constant.MqttConstant.LIVE_EVENT_BUS_KEY_MQTT_CONNECT_STATE
import com.ogawa.base.Constant.MqttConstant.LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE
import com.ogawa.base.Constant.MqttConstant.LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE2
import com.ogawa.base.Constant.MqttConstant.MQTT_STATE_CONNECTED
import com.ogawa.base.Constant.MqttConstant.MQTT_STATE_CONNECTING
import com.ogawa.base.Constant.MqttConstant.MQTT_STATE_UNCONNECT
import com.ogawa.base.bean.ReceiveMassageBean
import com.ogawa.base.mqtt.MqttManager
import com.ogawa.base.mqtt.MqttSendMsgCallback
import com.ogawa.base.utils.ActivityManager
import com.ogawa.base.utils.CommonUtil
import com.ogawa.base.utils.StringUtils
import com.ogawa.chair7808.bean.Massage7808Armchair
import com.ogawa.chair7808.bean.TempDevice7808StateBean
import com.ogawa.chair7808.cache.*
import com.ogawa.chair7808.manager.DataManager
import com.ogawa.chair7808.manager.TimeBean
import com.ogawa.chair7808.ui.dialog.AntiPinchDialog
import com.ogawa.chair7808.utils.Activity7808Utils
import com.ska.skautils.utilcode.util.ActivityUtils
import org.eclipse.paho.client.mqttv3.MqttMessage
import org.greenrobot.eventbus.EventBus
import org.json.JSONObject

/**
 * Activity 的基类封装
 * Created by HourGlassRemember on 2018/8/6.
 */
//MqttConnectListener, MqttReceiveListener
abstract class BaseMqtt7808Activity : BaseActivity() {
     var isFinishShow = false

    override fun initView(layoutId: Int) {
        super.initView(layoutId)
        LiveEventBus.get(LIVE_EVENT_BUS_KEY_END_TIME).observe(this, {
            LogUtils.e("nadadfame333==${javaClass.name}===top==${ActivityUtils.getTopActivity().javaClass.name}")

            if (javaClass.name == ActivityUtils.getTopActivity().javaClass.name) {
                publish(CommmandNum.FINISH, "4")
                if (!isFinishShow) {
                    isFinishShow = true
                    showFinishDialog(this, "-1") {
                        cancleFinishDialog()
                        isFinishShow = false;
                        if (!javaClass.name.contains("AdvancedMassageActivity")) {
                            ActivityUtils.finishToActivity(Home7808Activity7808::class.java, false)
                        }

                    }
                }
            }

        })

        LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE, ReceiveMassageBean::class.java).observe(this, {
            onReceiveMqttMsg(it.topic, it.message)
            changeActivity()
            changeViewByMqttMessage();
        })

        LiveEventBus.get(LIVE_EVENT_BUS_KEY_MQTT_CONNECT_STATE, Int::class.java).observe(this, {
            when (it) {
                MQTT_STATE_CONNECTING -> {
                    showloading()
                }
                MQTT_STATE_UNCONNECT -> {
                    cancleloading()
                    isHandOutAdvancedMassageActivity = false
                    lastAutoProgram = 0
                    DataManager.dataManager.clearData()
                    Massage7808Armchair.getInstance().tempDeviceStatusBean = null
//            LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE).post(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE)
//                Activity7808Utils.startHomeActivityClearTop(this)
//                        LiveEventBus.get(LIVE_EVENT_BUS_KEY_STATUS, Boolean::class.java).post(false)
                    refreshIcon(false)
                    titleBar.initData()
                    if (!CommonUtil.isActivityTop(SoftApActivity::class.java, this@BaseMqtt7808Activity)
                            && !CommonUtil.isActivityTop(SoftApOldActivity::class.java, this@BaseMqtt7808Activity)
                            && !CommonUtil.ActivityTop(this@BaseMqtt7808Activity).contains("WifiSettingsActivity")) {
                        ActivityUtils.finishToActivity(Home7808Activity7808::class.java, false)

                    }
                }
                MQTT_STATE_CONNECTED -> {
                    cancleloading()
                    refreshIcon(true)
                }
            }

        })
    }


     open fun refreshIcon(isConnect: Boolean){

    }
    /**
     * 界面跳转相关
     */
    private fun changeActivity() {
        val topActivity = ActivityManager.getInstance().currentActivity()
        deviceStatusBean?.let { bean ->
            //防夹 弹窗判断
            bean.antiPinchCheck?.let {
                if (it.isNotEmpty() && it != "0") {
                    if (!AntiPinchDialog.isShowAntiPinchDialog) {
                        AntiPinchDialog.isShowAntiPinchDialog = true
                        val antiPinchDialog = AntiPinchDialog()
                        antiPinchDialog.setBaseActivity(this)
                        antiPinchDialog.show(supportFragmentManager, "AntiPinchDialog")
                    }
                }
            }

            //肩部检测判断
            bean.shoulderDetectCheck?.let {
                if (it == "3" || it == "6") {
                    if (topActivity !is ScanShoulderActivity7808 || topActivity !is ShouldersAdjustmentActivity7808) {
                        Activity7808Utils.startScanShoulderActivity(this)
                        return
                    }
                }
            }
            if (isautoProgram) {
                if (!isHandOutProMasDetailActivity
                        && topActivity !is ProMasDetailActivity7808) {
                    Activity7808Utils.startProMasDetailActivity(this, autoProgramName)
                }
            } else if (isHandProgram) {
                if (!isHandOutAdvancedMassageActivity
                        && topActivity !is AdvancedMassageActivity7808) {
                    Activity7808Utils.startAdvancedMassageActivity(this)
                }
            }


        }
    }


    protected open fun changeViewByMqttMessage() {
//        LogUtils.i("${mActivity.localClassName}：处理消息")
    }


    fun onReceiveMqttMsg(topic: String?, message: MqttMessage?) {
        if (topic == null || message == null) {
            return
        }
        val msg = String(message.payload)

        try {
            if (topic.contains("up")) { //设备状态的消息
//                LogUtils.i("$TAG 处理up消息 ${topic} :   ${msg}")
                //elecTime  点击按摩
                //心跳包
                if (!msg.contains("fault") && !msg.contains("elecTime") && !msg.contains("heartbeat")) {

                    Massage7808Armchair.getInstance().tempDeviceStatusBean = GsonUtils.fromJson(msg, TempDevice7808StateBean::class.java)
                    Massage7808Armchair.getInstance().tempDeviceStatusBean?.functions?.let {

                        try {
                            val modelValue = it.autoProgram?.modelValue
                            if (StringUtils.getValue(modelValue) > 0) {
                                if (lastAutoProgram != StringUtils.getValue(modelValue)) {
                                    isHandOutProMasDetailActivity = false
                                    LogUtils.e("改变了：${lastAutoProgram}  : ${modelValue}")
                                }
                            }
                            if (it.autoProgram != null && it.autoProgram.modelValue != null) {
                                lastAutoProgram = StringUtils.getValue(modelValue)
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }

                        changeTime(it)
                        DataManager.dataManager.analysisDeviceStatusBean(it)
                    }

                } else if (msg.contains("fault")) { //设备故障码
                    val functions: String = JSONObject(msg).getString("functions")
                    val fault = JSONObject(functions).getString("fault")
                    val faultResult = JSONObject(fault).getString("modelValue")
                    Massage7808Armchair.getInstance().fault = faultResult
                }
            } else if (topic.contains("back")) { //发送消息的回复
//                LogUtils.e("$TAG 处理back消息 ${topic} :   ${msg}")
                val cmdResult: String = JSONObject(msg).getString("cmdResult")
                var sendState = 0
                when (cmdResult) {
                    "success" -> sendState = MqttSendMsgCallback.SUCCESS
                    "fail" -> sendState = MqttSendMsgCallback.FAIL
                    "timeout" -> sendState = MqttSendMsgCallback.TIMEOUT
                    "offline" -> sendState = MqttSendMsgCallback.OFFLINE
                }
            }
            LiveEventBus.get(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE2).post(LIVE_EVENT_BUS_KEY_RECEIVE_MESSAGE2)
            EventBus.getDefault().post(EVENT_BUS_KEY_RECEIVE_MESSAGE)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }


    open fun changeTime(bean: TempDevice7808StateBean.FunctionsBean){
        if(javaClass.name.contains("Home7808Activity7808")){
            if (bean.timeRemaining != null) {
                val split = bean.timeRemaining.modelValue.split(":")
                doUpDataTime(split[0].toInt(), split[1].toInt());
            }
            if (bean.runningStatus != null) {

                if (bean.runningStatus.modelValue == "2") {
                    pauseTime();
                } else if (bean.runningStatus.modelValue == "1") {

                    reStarTime()
                }
            }
        }

    }

    open fun publish(func: String?, model: String) {
        publish(func, model, "")
    }

    open fun publish(func: String?, model: String, addition: String?) {
        if (MqttManager.instance.isConnect) { //已连接
//            showloading()
            MqttManager.instance.publish(func, model, addition)
        } else { //未连接
            connectMqtt()
        }
    }

    /**
     * 连接Mqtt
     */

    private fun connectMqtt() {
        LogUtils.e(TAG, "connectMqtt")
        MqttManager.instance.buildClient()
//         MqttManager.getInstance().disconnect()
//        mHandler.postDelayed({
//            if (MqttManager.getInstance().connect()) {
//                showloading()
//                mHandler.postDelayed({
//                    cancleloading()
//                    ToastUtils.showShort("连接设备服务器失败")
//                    MqttManager.getInstance().disconnect()
//                }, 30 * 1000)
//            }
//        }, 500)
    }


}